package bold.storage;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;

/**
 * @author khaiLoon
 * @date 2018/9/21
 **/
public class JsonSql {
    public static void main(String[] args) throws IOException {
//        String table = "st_yqga_dm";
//        String table = "highway_grid_speed";
        String table = "highway_grid_info";
        String jsonPath = "/work/public/bold/storage/src/test/java/bold/storage/json.json";
        String result = "/work/public/bold/storage/src/test/java/bold/storage/jsonH.text";

        //读取文件
        Path readPath = Paths.get(jsonPath);
        Path writePath = Paths.get(result);
        String json = new String(Files.readAllBytes(readPath));

        List<LinkedHashMap> maps = JSON.parseArray(json, LinkedHashMap.class);

        //拼接sql  inster into table ("id","ch")  values (1,2,3)

        StringBuilder sqlAll = new StringBuilder(100000000);

        for (Map map : maps) {
            StringBuffer row = new StringBuffer(10000);
            String key = handelKey(map.keySet());
            String value = handelValue(map.values());

            row.append("insert into  ").append(table)
                    .append(key)
                    .append(" values ")
                    .append(" ")
                    .append(value)
                    .append(";")
                    .append(System.lineSeparator());
            sqlAll.append(row);
        }
        Files.write(writePath, sqlAll.toString().getBytes(), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
        System.out.println("write sql end");
        //传入枚举对象，打开追加开关
        //System.out.println(sqlAll.toString());
    }

    /**
     * 解析 table 以后  values 以前
     */
    public static String handelKey(Set<String> keySet) {
        StringBuilder sb = new StringBuilder();
        for (String key : keySet) {
            sb.append("\"").append(key).append("\"").append(",");
        }
        sb = sb.deleteCharAt(sb.length() - 1)
                .insert(0, "(")
                .append(")");
        return sb.toString();
    }

    public static String handelValue(Collection<Object> keySet) {
        StringBuilder sb = new StringBuilder();
        for (Object obj : keySet) {
            String key = String.valueOf(obj);
            sb.append("'").append(key).append("'").append(",");
        }
        sb = sb.deleteCharAt(sb.length() - 1)
                .insert(0, "(")
                .append(")");
        return sb.toString();
    }

}
